import qs from 'qs';
import request from './request';
import { setGlobalData } from './globalData';
import { setStorageSync } from '@tarojs/taro';
import { wxData, CacheUserInfo } from '../constant/cache';

/**
 * 常用CRUD
 */

export default {
  /**
   * 查询
   * @param params
   * @returns {Object}
   */
  read(path, params) {
    return request({ url: `${path}/read?${qs.stringify(params)}` });
  },
  /**
   * 新建
   *
   * @export
   * @param {any} params
   * @returns
   */
  create(path, params) {
    return request({
      url: `${path}/create`,
      method: 'post',
      header: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(params)
    });
  },
  /**
   * 更新
   *
   * @export
   * @param {any} params
   * @returns
   */
  update(path, params) {
    return request({
      url: `${path}/update`,
      method: 'post',
      header: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(params)
    });
  },
  /**
   * 删除
   *
   * @export
   * @param {any} params
   * @param {string} [method="post"]
   * @returns
   */
  delete(path, params, method = 'post') {
    return request({
      url: `${path}/delete?${qs.stringify(params)}`,
      method: method
    });
  },
  /**
   * 通用查询，通过配置pathname来确定url路径
   *
   * @param {any} pathname 基准路径，eg： www.12.com/a/b?123 /a:基础url一般在service实例化时设置，/b:基准路径，配置http:开头 可跳过基础路径进行跨api访问
   * @param {any} params 请求参数
   * @param {string} [method="post"]
   * @returns
   * @memberof baseService
   */
  query(pathname, params, method = 'get') {
    let url = '';
    if (/http\:/.test(pathname)) {
      pathname = pathname.replace('http:', '');
      url = `${pathname}`;
    } else {
      if (!/^\//g.test(pathname)) {
        pathname = `/${pathname}`;
      }
      url = pathname;
    }
    return request({
      url: `${url}${Object.keys(params).length ? '?' : ''}${qs.stringify(params, {
        skipNulls: true
      })}`,
      method: method
    });
  },
  /**
   *通用post方法，类似query方法
   *
   * @param {any} pathname
   * @param {object} body
   * @returns
   * @memberof baseService
   */
  post(pathname, body, opt = { isForm: false }) {
    const { isForm } = opt;
    let url = '';
    if (/http\:/.test(pathname)) {
      pathname = pathname.replace('http:', '');
      url = `${pathname}`;
    } else {
      if (!/^\//g.test(pathname)) {
        pathname = `/${pathname}`;
      }
      url = pathname;
    }
    return request({
      url: url,
      method: 'post',
      header: {
        'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'application/json'
      },
      data: body
    });
  },
  queryUserInfo(cb = null) {
    return this.query('/user/user/getAuthenticationUser', {}).then((res) => {
      setGlobalData(wxData.userInfo, res);
      setStorageSync(CacheUserInfo, res);
      cb && cb(res);
    });
  }
};
